<template>
  <div>
    <el-button type="primary" @click="openDialog()">新增车辆</el-button>
    <el-table :data="tableData" style="width: 100%; margin-top: 16px">
      <el-table-column type="index" :index="(index) => index + 1" label="编号" width="80" />
      <el-table-column prop="ibName" label="车主" />
      <el-table-column prop="carNo" label="车牌号" />
      <el-table-column prop="carLicense" label="品牌" />
      <el-table-column prop="carParking" label="停车位" />
      <el-table-column prop="carDisplacement" label="排量" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 16px"
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="90px">
        <el-form-item label="车主">
          <el-select v-model="form.ibId" placeholder="请选择车主" @change="handleOwnerChange" clearable :disabled="residentsLoading">
            <el-option v-for="resident in residents" :key="resident.ibId" :label="resident.ibName" :value="resident.ibId" />
          </el-select>
          <div v-if="residentsLoading" class="el-loading-text">加载中...</div>
          <div v-if="residentsError" class="text-danger">{{ residentsError }}</div>
        </el-form-item>
        <el-form-item label="车牌号">
          <el-input v-model="form.carNo" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="form.carLicense" />
        </el-form-item>
        <el-form-item label="停车位">
          <el-input v-model="form.carParking" />
        </el-form-item>
        <el-form-item label="排量">
          <el-input v-model="form.carDisplacement" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import {  postRequest, putRequest, deleteRequest ,getRequest} from '@/utils/request';


const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增车辆');
const form = reactive({
  id: null,
  ibId: '',
  ibName: '',
  carNo: '',
  carLicense: '',
  carParking: '',
  carDisplacement: ''
});
const residents = ref([]);
const residentsLoading = ref(false);
const residentsError = ref('');

function fetchData() {
  postRequest('/car/getCarByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data) {
      tableData.value = Array.isArray(res.data.data.cars) ? res.data.data.cars : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    tableData.value = [];
    total.value = 0;
  });
}

function fetchResidents() {
  residentsLoading.value = true;
  residentsError.value = '';
  getRequest('/inhabitants/getInhabitantsList').then(res => {
    console.log('居民列表API响应:', res);
    if (res && res.data && Array.isArray(res.data.data)) {
      console.log('原始居民数据:', res.data.data);
      const validResidents = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => ({
          ibId: String(element.id), // 确保ID为字符串类型
          ibName: element.ibName || element.name || element.username || `用户${element.id}`
        }));
      residents.value = validResidents;
      console.log('转换后的居民列表:', residents.value);
      if (validResidents.length === 0) {
        residentsError.value = '未找到居民数据，请联系系统管理员';
      }
    } else {
      residentsError.value = '居民数据格式不正确';
      console.error('居民数据格式错误:', res);
    }
  }).catch(error => {
    residentsError.value = '获取居民列表失败: ' + (error.message || '网络错误');
    console.error('获取居民列表失败:', error);
  }).finally(() => {
    residentsLoading.value = false;
  });
}

function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑车辆';
    Object.assign(form, row);
    form.ibId = row.ibId ? String(row.ibId) : '';
    form.ibName = row.ibName || '';
  } else {
    dialogTitle.value = '新增车辆';
    form.id = null;
    form.ibId = '';
    form.ibName = '';
    form.carNo = '';
    form.carLicense = '';
    form.carParking = '';
    form.carDisplacement = '';
  }
  dialogVisible.value = true;
}

function handleOwnerChange(ibId) {
  console.log('选中的车主ID:', ibId);
  // 确保比较时类型一致
  const selectedResident = residents.value.find(resident => resident.ibId === String(ibId));
  console.log('找到的车主信息:', selectedResident);
  if (selectedResident) {
    form.ibName = selectedResident.ibName;
    console.log('更新后的车主姓名:', form.ibName);
  } else {
    form.ibName = '';
    console.warn('未找到ID为', ibId, '的车主');
  }
}

function handleSubmit() {
  if (form.id) {
    putRequest('/car/updateCarById', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  } else {
    postRequest('/car/addCar', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  }
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/car/deleteCarById/${id}`).then(() => {
      fetchData();
    });
  }).catch(() => {});
}

function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

onMounted(() => {
  fetchData();
  fetchResidents();
});
</script>
